package com.ruoyi.web.controller.members;

import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.constant.MembersConstants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.MembersStatus;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.flowable.common.constant.ProcessConstants;
import com.ruoyi.flowable.common.enums.FlowComment;
import com.ruoyi.flowable.service.ISysFormService;
import com.ruoyi.system.domain.ActReProcdef;
import com.ruoyi.system.domain.SysForm;
import com.ruoyi.system.service.IActReProcdefService;
import com.ruoyi.system.service.ISysUserService;
import org.flowable.engine.HistoryService;
import org.flowable.engine.IdentityService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.members.domain.SysMembers;
import com.ruoyi.members.service.ISysMembersService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 教职工Controller
 * 
 * @author ruoyi
 * @date 2025-09-16
 */
@RestController
@RequestMapping("/system/members")
public class SysMembersController extends BaseController
{
    @Autowired
    private ISysMembersService sysMembersService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IActReProcdefService actReProcdefService;

    @Autowired
    private IdentityService identityService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private HistoryService historyService;

    @Autowired
    private ISysFormService sysFormService;
    /**
     * 人才智库 - 教职工管理 - 查询教职工（会员）列表
     */
//    @PreAuthorize("@ss.hasPermi('system:members:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysMembers sysMembers)
    {
        /*
        startPage();
        List<SysMembers> list = sysMembersService.selectSysMembersList(sysMembers);
        return getDataTable(list);
         */

        //MybatisPlus - 条件分页查询
        Page<SysMembers> objectPage = new Page<>(sysMembers.getPageNum(), sysMembers.getPageSize());
        LambdaQueryWrapper<SysMembers> sysMembersLambdaQueryWrapper = new LambdaQueryWrapper<SysMembers>();
        if (sysMembers.getMembersName() != null){
            sysMembersLambdaQueryWrapper.like(SysMembers::getMembersName, sysMembers.getMembersName());
        }
        if (sysMembers.getMembersNum() != null){
            sysMembersLambdaQueryWrapper.eq(SysMembers::getMembersNum, sysMembers.getMembersNum());
        }
        if (sysMembers.getMembersTel() != null){
            sysMembersLambdaQueryWrapper.eq(SysMembers::getMembersTel, sysMembers.getMembersTel());
        }
        Page<SysMembers> page = sysMembersService.page(objectPage, sysMembersLambdaQueryWrapper);
        return new TableDataInfo(page.getRecords(), page.getTotal(), page.getCurrent(), page.getSize());
    }

    /**
     * 导出会员列表
     */
    @PreAuthorize("@ss.hasPermi('system:members:export')")
    @Log(title = "会员", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysMembers sysMembers)
    {
        //MybatisPlus - 条件分页查询
        LambdaQueryWrapper<SysMembers> sysMembersLambdaQueryWrapper = new LambdaQueryWrapper<SysMembers>();
        if (sysMembers.getMembersName() != null){
            sysMembersLambdaQueryWrapper.like(SysMembers::getMembersName, sysMembers.getMembersName());
        }
        if (sysMembers.getMembersNum() != null){
            sysMembersLambdaQueryWrapper.eq(SysMembers::getMembersNum, sysMembers.getMembersNum());
        }
        if (sysMembers.getMembersTel() != null){
            sysMembersLambdaQueryWrapper.eq(SysMembers::getMembersTel, sysMembers.getMembersTel());
        }

        List<SysMembers> list = sysMembersService.list(sysMembersLambdaQueryWrapper);
        ExcelUtil<SysMembers> util = new ExcelUtil<SysMembers>(SysMembers.class);
        util.exportExcel(response, list, "教职工数据","教职工信息统计表");
    }

    /**
     * 人才智库 - 教职工管理 - 详细（会员ID）
     */
//    @PreAuthorize("@ss.hasPermi('system:members:query')")
    @GetMapping(value = "/{membersId}")
    public AjaxResult getInfo(@PathVariable("membersId") Long membersId)
    {
        return success(sysMembersService.getById(membersId));
    }


    /**
     * 人才智库 - 教职工管理 - 详细（会员工会）
     */
    @GetMapping("/membersNum")
    public AjaxResult getInfoByMembersNum(){
        //判断是否是管理员
        if (MembersConstants.ADMIN_NAME.equals(SecurityUtils.getUsername())){
            return success(new SysMembers());
        }
        //根据会员ID查询会员
        List<SysUser> list = sysUserService.list(new LambdaQueryWrapper<>(SysUser.class).eq(SysUser::getUserName, SecurityUtils.getUsername()));
        if (list.size() == 0){
            return error(MembersStatus.USER_NOT_EXIST.getInfo());
        }
        //根据会员ID查询教职工
        List<SysMembers> list1 = sysMembersService.list(new LambdaQueryWrapper<>(SysMembers.class).eq(SysMembers::getMembersNum, list.get(0).getUserName()));
        if (list1.size() == 0){
            return error(MembersStatus.TEACHER_NOT_EXIST.getInfo());
        }
        return success(list1.get(0));
    }

    /**
     * 人才智库 - 教职工管理 - 新增
     */
    @PreAuthorize("@ss.hasPermi('system:members:add')")
    @Log(title = "会员", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysMembers sysMembers)
    {
        MembersStatus membersStatus = sysMembersService.saveMembers(sysMembers);

        return MembersConstants.SUCCESS_CODE.equals(membersStatus.getCode())?success(membersStatus.getInfo()):error(membersStatus.getInfo());
    }

    /**
     * 人才智库 - 教职工管理 - 修改
     */
    @PreAuthorize("@ss.hasPermi('system:members:edit')")
    @Log(title = "会员", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysMembers sysMembers)
    {
        //根据ID查询教职工
        SysMembers member = sysMembersService.getById(sysMembers.getMembersId());
        //判断教职工是否存在（ID）
        if (member == null){
            return error(MembersStatus.TEACHER_NOT_EXIST.getInfo());
        }
        //是否修改标志
        boolean flag = false;
        //修改工号
        if (sysMembers.getMembersNum() != member.getMembersNum()){
            flag = true;
        }
        //修改昵称
        if (sysMembers.getMembersName() != member.getMembersName()){
            flag = true;
        }

        //根据ID查询用户
        SysUser user = sysUserService.getById(member.getUserId());
        //判断用户是否存在
        if (user == null){
            return error(MembersStatus.USER_NOT_EXIST.getInfo());
        }

        //修改用户部门
        user.setDeptId(sysMembers.getDeptId());
        //修改用户邮箱
        user.setEmail(sysMembers.getMembersEmail());
        //修改用户手机号码
        user.setPhonenumber(sysMembers.getMembersTel());
        //修改用户性别
        user.setSex(sysMembers.getMembersSex());
        //修改用户头像
        user.setAvatar(sysMembers.getMembersImg());
        //判断是否修改工号、昵称
        if (flag){
            //修改用户名
            user.setUserName(sysMembers.getMembersNum().toString());
            //修改用户昵称
            user.setNickName(sysMembers.getMembersName());
        }
        //更新用户表
        sysUserService.updateById(user);
        //更新教职工表
        return toAjax(sysMembersService.updateById(sysMembers));
    }

    /**
     * 人才智库 - 教职工管理 - 删除
     */
    @PreAuthorize("@ss.hasPermi('system:members:remove')")
    @Log(title = "会员", businessType = BusinessType.DELETE)
	@DeleteMapping("/{membersIds}")
    public AjaxResult remove(@PathVariable Long[] membersIds)
    {
        MembersStatus membersStatus = sysMembersService.deleteSysMembersByMemsIds(membersIds);
        return MembersConstants.SUCCESS_CODE.equals(membersStatus.getCode())?success(membersStatus.getInfo()):error(membersStatus.getInfo());
    }


    /**
     * 人才智库 - 教职工管理 - 申请入会
     */
    @PostMapping("/membersFlowable")
    public AjaxResult membersFlowable(@RequestBody SysMembers sysMember) {
        // 修改
        boolean b = sysMembersService.updateById(sysMember);

        //修改失败
        if(!b){
            return error(MembersStatus.OPERATE_FAIL.getInfo());
        }

        // 触发审批流 - 申请入会
        // 进行审批操作
        try {
            sysMember.setCreateBy(getUsername());
            // 查询入会流程定义
            LambdaQueryWrapper<ActReProcdef> actReProcdefLambdaQueryWrapper = new LambdaQueryWrapper<>();
            // 流程定义名称
            actReProcdefLambdaQueryWrapper.eq(ActReProcdef::getName, "申请入会审批流程");
            // version降序
            actReProcdefLambdaQueryWrapper.orderByDesc(ActReProcdef::getVersion);
            List<ActReProcdef> list = actReProcdefService.list(actReProcdefLambdaQueryWrapper);

            // 判断list是否为空或长度是否为0
            if (list != null && !list.isEmpty()) {
                // 判断流程是否已经开启
                if (list.get(0).getSuspensionState() != 1) {
//                    return AjaxResult.result(MembersConstants.MEMBERS_STATUS_M14000, SystemTypeConstants.SYSTEM_TYPE_MEMBER);
                }

                // 启动流程实例
                HashMap<String, Object> variables = new HashMap<>();
                variables.put("commonClass", sysMember);
//                variables.put("action", "approve");
                // 绑定表单
                SysForm sysForm = new SysForm();
                sysForm.setFormName("申请入会审批流程表单");
                List<SysForm> sysForms = sysFormService.selectSysFormList(sysForm);
                if (sysForms.size() > 0) {
                    // 集合根据id降序
                    sysForms.sort(Comparator.comparing(SysForm::getFormId).reversed());
                    variables.put("formJson", sysForms.get(0).getFormContent());
                }

                SysUser user = SecurityUtils.getLoginUser().getUser();
                // 设置流程发起人
                identityService.setAuthenticatedUserId(user.getUserId().toString());
                variables.put(ProcessConstants.PROCESS_INITIATOR, user.getUserId());
                // 流程发起，跳过发起人节点
                ProcessInstance processInstance = runtimeService.startProcessInstanceById(list.get(0).getId(), variables);
                // 给第一步申请人节点设置任务执行人和意见
                Task task = taskService.createTaskQuery().processInstanceId(processInstance.getProcessInstanceId()).singleResult();
                if (Objects.nonNull(task)) {
                    taskService.addComment(task.getId(), processInstance.getProcessInstanceId(), FlowComment.NORMAL.getType(), user.getNickName() + "发起入会流程申请");
                    taskService.complete(task.getId(), variables);
                }

            } else {

                add(sysMember);
            }
            return success("入会申请提交成功");
        } catch (Exception e) {
            e.printStackTrace();
//            return AjaxResult.result(MembersConstants.MEMBERS_STATUS_M14001, SystemTypeConstants.SYSTEM_TYPE_MEMBER);
        }

        return null;
    }
}
